package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

@Component
public class ManagerFilter extends ZuulFilter {
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 表示在请求前执行pre （后执行post）
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 数字越小越先执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否开启
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤的内容（执行的操作）
     * setsendzullRespponse（false）表示不再继续执行
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        if (request.getRequestURL().indexOf("login")>0){
            return null;
        }
        String header = request.getHeader("Authorization");
        if (header!=null&&!"".equals(header)){
            if (header.startsWith("Bearer ")){
                String  token = header.substring(7);
                try {
                    //验证令牌
                    Claims claims = jwtUtil.parseJWT(token);
                    String  roles = (String) claims.get("roles");
                    if (roles!=null&&roles.equals("admin")){
                        //头信息转发并放行
                        request.setAttribute("claims_admin",token);
                        requestContext.addZuulRequestHeader("Authorization",header);
                        return null;
                    }
                }catch (Exception e){
                    //终止运行
                   requestContext.setSendZuulResponse(false);
                   requestContext.setResponseStatusCode(403);
                   requestContext.setResponseBody("权限不足");
                   requestContext.getResponse().setContentType("text/html;charset=utf-8");
                }
            }
        }

        return null;
    }
}
